package com.travel.sight.interceptor;

import com.alibaba.fastjson.JSON;
import com.travel.common.vo.MemberRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.concurrent.TimeUnit;

import static com.travel.common.constant.AuthServerConstant.LOGIN_USER;

@Component
public class SightInterceptor implements HandlerInterceptor {

    final
    StringRedisTemplate redisTemplate;

    public SightInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 用户有操作则重置redis中用户的ttl为 30min
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String loginUser = redisTemplate.opsForValue().get(LOGIN_USER);
        MemberRespVo memberRespVo = JSON.parseObject(loginUser, MemberRespVo.class);

        //后台的请求直接放行 后台url带有api
        //http://localhost:88/api/sight/attractioninfo/list
        String uri = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/sight/attractioninfo/list", uri);
        if(match){
            return true;
        }

        if (memberRespVo != null) {
            // 重置TTL为30分钟
            redisTemplate.expire(LOGIN_USER, 30, TimeUnit.MINUTES);
            return true;
        } else {
            // 未登录，进行跳转
            response.sendRedirect("http://auth.travel.com/login.html");
            return false;
        }
    }
}
